package com.oa.kq.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.service.SequenceService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.kq.entity.Attendance;
import com.oa.kq.service.AttendanceService;
import com.oa.utils.ExcelView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
// todo kq的controller 没有整好，ModelAndView

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
// todo kq是错的， @RestController注解的类下面 return ModleAndView 的方法
@Controller
@RequestMapping(value = "/**/oa/kq/attendance")
@Api(tags = {"擎勤科技考勤记录表-操作接口"})
public class AttendanceController {

    static Logger logger = LoggerFactory.getLogger(AttendanceController.class);

    @Autowired
    private AttendanceService attendanceService;

    @Autowired
    private SequenceService seqService;

    /**
     * 跳转到attendanceIndex.html
     */
    // todo 会一直在终端输出  /attendance/oa/oa/oa/kq/ ...
    @RequestMapping(value = "/attendanceIndex")
    public ModelAndView attendanceIndex() {
        ModelAndView mv = new ModelAndView();
        Date date = new Date();
        Tips tips = new Tips();
        tips.setMsg("成功");
        try {
            User user = LoginUtils.getCurrentUserInfo();
            // 获取用户头像：如果用户表没有，那么去微信的表找

            if (user.getHeadimgurl() == null) {

            }
            //用户名如果为空则去微信的表找,第三方一般返回昵称 by chenyc 20170320
            if (user.getUsername() == null) {
            }
            mv.addAllObjects(attendanceService.getAllAttendance(date, user));
        } catch (Exception e) {
            // TODO: handle exception
            logger.error(e.toString(), e);
            tips.setErrMsg("访问首页异常");
            mv.addObject(tips);
        }
        return mv;
    }

    /**
     * 新增一条数据
     *
     * @判断如果传递的groupid是有值的就是更新不是新增操作
     * @cdate 2020/1/10 11:19
     * @cauthor 林钰坤
     */
    @ResponseBody
    @RequestMapping(value = "/insertAttendance")
    public Result insertAttendance(Attendance attendance, String btnPoi, String deptid) {
        Map<String, Object> insertAttendance = new HashMap<>();
        Tips tips = new Tips("成功");
        try {
            insertAttendance = attendanceService.insertAttendance(attendance, btnPoi, deptid);
        } catch (Exception e) {
            tips.setErrMsg(e.getMessage());
            insertAttendance.put("tips", tips);
        }
        return Result.ok().setData(insertAttendance).setTips(LangTips.fromTips(tips));
    }

    /**
     * 查询统计页面的数据
     */
    @ResponseBody
    @RequestMapping(value = "/countAttendance")
    public Result countAttendance(String month) {
        Map<String, Object> count = attendanceService.getThisMonthCount(month);
        return Result.ok().setData(count);
    }

    /**
     * 判断是否在公司范围
     *
     * @cContent 根据group去获取地点范围以及wifi判断
     * @cd2020/1/4 14:02
     * @cauthor LinYuKun
     */
    @ResponseBody
    @RequestMapping(value = "/isHere")
    public boolean isHere(Attendance attendance, String bssid, String deptid) {
        return attendanceService.isHere(attendance, bssid, deptid);
    }

    /**
     * 查询今日总工时
     */
    @ResponseBody
    @RequestMapping(value = "/todayCount")
    public Result todayCount() {

        User user = LoginUtils.getCurrentUserInfo();

        Attendance attendance = new Attendance();
        attendance.setUserid(user.getUserid());
        // 获取今日工时
        Date date = new Date();
        attendance.setWorkTime(date);

        Map<String, Object> todayCount = attendanceService.getTodayCount(attendance);
        return Result.ok().setData(todayCount);
    }

    /**
     * 跳转到attendanceDayRecord.html：返回数据和view
     * 点击日历下方的打卡时间，跳转到attendanceDayRecord.html查看详情
     */
    @RequestMapping(value = "/attendanceDayRecord")
    public ModelAndView attendanceDayRecord(@ModelAttribute("user") User user, BindingResult result, @RequestParam String date) {
        ModelAndView mv = new ModelAndView();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse;
        try {
            parse = sdf.parse(date);
            mv.addAllObjects(attendanceService.getAllAttendance(parse, user));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * 查询某月打卡记录
     */
    @ResponseBody
    @RequestMapping(value = "/monthRecord")
    public Result monthRecord(@ModelAttribute("user") User user, @RequestParam String month) {
        Map<String, Object> m = new HashMap<>();
        Tips tips = new Tips("成功");
        if (StringUtils.isEmpty(user)) {
            tips.setErrMsg("请传递user");
        } else {
            m = attendanceService.getMonthRecord(month, user);
        }
        return Result.ok().setData(m).setTips(LangTips.fromTips(tips));
    }

    /**
     * 根据条件查询考勤
     *
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkWorkAttendance")
    public Result checkWorkAttendance(@RequestParam Map<String, Object> params) {
        return Result.ok("成功").setData(attendanceService.getCheckWorkAttendance(params));
    }


    /**
     * 跳转到attendanceMonth.html：返回数据和view
     */
    @RequestMapping(value = "/attendanceMonth")
    public ModelAndView attendanceMonth(User user) {
        ModelAndView mv = new ModelAndView();
        Date date = new Date();
        mv.addAllObjects(attendanceService.getAllAttendance(date, user));
        return mv;
    }

    /**
     * 查询某日打卡记录:只返回数据
     */
    @ResponseBody
    @RequestMapping(value = "/dayRecord")
    public Result dayRecord(@ModelAttribute("user") User user, BindingResult result, @RequestParam String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse;
        try {
            parse = sdf.parse(date);
            return Result.ok().setData(attendanceService.getAllAttendance(parse, user));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return Result.error();
        }
    }


    /**
     * 查询某日打卡记录：根据group等
     * poi表示第几次上下班打卡
     * btnState表示上班还是下班
     *
     * @cdate 2020/1/8 18:10
     * @cauthor LinYuKun
     */
    @ResponseBody
    @RequestMapping(value = "/dayRecordList")
    public Result dayRecordList(@RequestParam String date, @RequestParam String deptid) {
        Map<String, Object> m = new HashMap();
        Tips tips = new Tips("成功");
        Map<String, Object> data = new HashMap();
        if (StringUtils.isEmpty(deptid)) {
            throw new BizException("请传递deptid");
        }
        data = attendanceService.getTimeAttList(date, deptid);
        return Result.ok().setData(data);
    }

    /**
     * 查询团队统计数据
     */
    @ResponseBody
    @RequestMapping(value = "/getTeamRecord")
    public Result getTeamRecord(@RequestParam String date, @RequestParam String deptid) {
        return Result.ok().setData(attendanceService.getTeamRecord(date, deptid));
    }

    /**
     * 查询某个时刻的打卡信息：用于查询备注
     */
    @ResponseBody
    @RequestMapping(value = "/getTimeAttendance")
    public Attendance getTimeAttendance(@ModelAttribute("user") User user, BindingResult result, @RequestParam String date) {
        return attendanceService.getTimeAttendance(date, user);
    }

    /**
     * 跳转打卡详细页面 attendanceDetail.html
     */
    @RequestMapping(value = "/attendanceDetail")
    public ModelAndView attendanceDetail(String date) {
        ModelAndView mv = new ModelAndView();
        mv.addAllObjects(attendanceService.getTeamRecord(date, ""));
        return mv;
    }

    /**
     * 跳转设置页面kqSetting.html
     */
    @RequestMapping(value = "/kqSetting")
    public ModelAndView kqSetting() {
        ModelAndView mv = new ModelAndView();
        return mv;
    }


    /**
     * 跳转到查询页面listAttendance.jsp
     */
    @RequestMapping(value = "/listAttendance")
    public ModelAndView listAttendance(@ModelAttribute("attendance") Attendance attendance, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("data", attendance);
        return mv;
    }

    /**
     * 跳转到新增页面addAttendance.jsp
     */
    @RequestMapping(value = "/addAttendance")
    public ModelAndView addAttendance() {

        ModelAndView mv = new ModelAndView();
        Attendance attendance = new Attendance();
        mv.addObject("data", attendance);
        return mv;
    }

    /**
     * 跳转到修改页面editAttendance.jsp
     */
    @RequestMapping(value = "/editAttendance")
    public ModelAndView editAttendance(@ModelAttribute("attendance") Attendance attendance, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        attendance = attendanceService.selectOneObject(attendance); // 根据ID读取
        mv.addObject("data", attendance);
        return mv;
    }

    /**
     * 请求需带json后缀,如selectListAttendanceByPage.json 根据条件查询数据对象列表
     */
    @RequestMapping(value = "/selectListAttendanceByPage")
    public ModelAndView selectListAttendanceByPage(@ModelAttribute("attendance") Attendance attendance, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();

        List<Attendance> attendanceList = attendanceService.selectListByWhere(attendance); // 列出Attendance列表
        mv.addObject("data", attendanceList);
        Tips tips = new Tips("查询成功");
        mv.addObject("tips", tips);
        return mv;
    }

    /**
     * 根据主键删除1条数据
     */
    @RequestMapping(value = "/deleteAttendanceByPk")
    public ModelAndView deleteAttendanceByPk(@ModelAttribute("attendance") Attendance attendance, BindingResult result) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功删除一条数据");
        attendanceService.deleteByPk(attendance);
        mv.addObject("tips", tips);
        return mv;
    }

    /**
     * 根据主键修改一条数据
     */
    @RequestMapping(value = "/updateAttendanceByPk")
    public ModelAndView updateAttendanceByPk(@ModelAttribute("attendance") Attendance attendance, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功更新一条数据");
        attendanceService.updateByPk(attendance);
        mv.addObject("data", attendance);
        mv.addObject("tips", tips);
        return mv;
    }

    @RequestMapping(value = "/updateSomeFileByPk", method = RequestMethod.POST)
    public Result editKqAttendance(@RequestBody Attendance attendance) {
        int i = attendanceService.updateSomeFieldByPk(attendance);
        return Result.ok("成功更新一条数据").setData(i);
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/batchDeleteAttendance")
    public ModelAndView batchDeleteAttendance(@RequestParam("id[]") String[] id) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功删除" + id.length + "条数据");
        List<Attendance> list = new ArrayList<Attendance>();
        for (int i = 0; i < id.length; i++) {
            Attendance attendance = new Attendance();
            attendance.setId(id[i]);
            list.add(attendance);
        }
        attendanceService.batchDelete(list);
        mv.addObject("tips", tips);
        return mv;
    }

    /*
     * 导出到excel
     *
     * @return
     */
    @RequestMapping(value = "/exportAttendanceToExcel")
    public ModelAndView exportAttendanceToExcel(@ModelAttribute("attendance") Attendance attendance, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功导出数据");
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
            titles.add("id");
            titles.add("userid");
            titles.add("work_longitude");
            titles.add("work_latitude");
            titles.add("work_address");
            titles.add("work_time");
            titles.add("state");
            titles.add("lc_state");
            dataMap.put("titles", titles);
            List<Attendance> AttendanceList = attendanceService.selectListByWhere(attendance);
            List<Map<String, Object>> allList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < AttendanceList.size(); i++) {
                Map<String, Object> row = new HashMap<String, Object>();
                row.put("var1", AttendanceList.get(i).getId());
                row.put("var2", AttendanceList.get(i).getUserid());
                row.put("var3", AttendanceList.get(i).getWorkLongitude());
                row.put("var4", AttendanceList.get(i).getWorkLatitude());
                row.put("var5", AttendanceList.get(i).getWorkAddress());
                row.put("var6", AttendanceList.get(i).getWorkTime());
                row.put("var7", AttendanceList.get(i).getState());
                row.put("var8", AttendanceList.get(i).getLcState());
                allList.add(row);
            }
            dataMap.put("varList", allList);
            ExcelView erv = new ExcelView();
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            tips.setErrMsg("导出数据异常");
        }
        mv.addObject("tips", tips);
        return mv;
    }

    /**
     * 获取当天的考勤班次
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUserVeryDaySchedule", method = RequestMethod.GET)
    public Result getUserVeryDaySchedule() {
        Tips tips = new Tips("查询成功");
        List<Map<String, Object>> userVeryDaySchedule = null;
        try {
            userVeryDaySchedule = attendanceService.getUserVeryDaySchedule();
        } catch (Exception e) {
            tips.setErrMsg(e.getMessage());
            logger.error("", e);
        }
        return Result.ok("查询成功").setData(userVeryDaySchedule).setTips(LangTips.fromTips(tips));
    }

    @ResponseBody
    @ApiOperation(value = "擎勤科技考勤记录表-查询列表", notes = " ")
    @ApiEntityParams(Attendance.class)
    @ApiResponses({@ApiResponse(code = 200, response = Attendance.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listAttendance(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        QueryWrapper<Attendance> qw = QueryTools.initQueryWrapper(Attendance.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = attendanceService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    @ResponseBody
    @ApiOperation(value = "擎勤科技考勤记录表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Attendance.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addAttendance(@RequestBody Attendance attendance) {
        attendanceService.save(attendance);
        return Result.ok("add-ok", "添加成功！");
    }

    @ResponseBody
    @ApiOperation(value = "擎勤科技考勤记录表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delAttendance(@RequestBody Attendance attendance) {
        attendanceService.removeById(attendance);
        return Result.ok("del-ok", "删除成功！");
    }

    @ResponseBody
    @ApiOperation(value = "擎勤科技考勤记录表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Attendance.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editAttendance(@RequestBody Attendance attendance) {
        attendanceService.updateById(attendance);
        return Result.ok("edit-ok", "修改成功！");
    }

    @ResponseBody
    @ApiOperation(value = "擎勤科技考勤记录表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = Attendance.class, props = {}, remark = "擎勤科技考勤记录表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = Attendance.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        attendanceService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ResponseBody
    @ApiOperation(value = "擎勤科技考勤记录表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelAttendance(@RequestBody List<Attendance> attendances) {
        User user = LoginUtils.getCurrentUserInfo();
        if (attendances.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<Attendance> datasDb = attendanceService.listByIds(attendances.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<Attendance> can = new ArrayList<>();
        List<Attendance> no = new ArrayList<>();
        for (Attendance data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            attendanceService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ResponseBody
    @ApiOperation(value = "擎勤科技考勤记录表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Attendance.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(Attendance attendance) {
        Attendance data = (Attendance) attendanceService.getById(attendance);
        return Result.ok().setData(data);
    }

}
